import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import baseService from 'share/base.service';
import LoanService from 'containers/finance-setting/loan-max/loan-service';
import { Form, Switch, Input, Select, message, InputNumber, Button } from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class LoanRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      currencyList: [],
      saveLoading: false,
      record: {},
      typeList: []
    }
  }

  componentWillMount() {
    Promise.all([
      baseService.getAllCurrencyList(),
      LoanService.getTypeList(this.props.setOfBooksId)
    ]).then(res => {
      this.setState({
        currencyList: res[0].data.rows,
        typeList: res[1].data
      });
    }).catch(() => {
      message.error(messages('finance-setting.key154')/*系统异常*/);
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.show === this.props.show)
      return;
    if (!nextProps.show) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      record: nextProps.editRecord
    },() => {
      LoanService.getTypeList(nextProps.setOfBooksId).then(res => {
        this.setState({typeList: res.data});
      }).catch(() => {
        message.error(messages('finance-setting.key154')/*系统异常*/);
      });
    }) ;
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const { record, typeList } = this.state;
        let params = Object.assign({},record,values);
        record.amountMax && !values.amountMax && (params.amountMax = null);
        params.setOfBooksId = params.setOfBooksId ? params.setOfBooksId : this.props.setOfBooksId;
        typeList.map(item => {
          item.id === params.loanTypeId && (params.loanAmountType = item.description);
        });
        this.setState({saveLoading: true});
        let url = params.id ? 'updateLoanRule' : 'saveLoanRule';
        LoanService[url](params).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({saveLoading: false});
        });
      }
    })
  };

  render(){
    const { currencyList, saveLoading, record, typeList } = this.state;
    const { setOfBooksName } = this.props;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Form>
          <FormItem className="priority-wrap"
                    label={messages('common.column.status')/*状态*/} {...formItemLayout}>
            {getFieldDecorator('enabled',{
              rules: [{
                required: true
              }],
              initialValue: typeof record.enabled === "boolean" ? record.enabled : true,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem className="priority-wrap"
                    label={messages('finance-setting.key73'/*所属帐套*/)} {...formItemLayout}>
            {getFieldDecorator('setOfBooksName',{
              rules: [{
                required: true
              }],
              initialValue: record.setOfBooksName ? record.setOfBooksName : setOfBooksName
            })(
              <Input disabled={true}/>
            )}
          </FormItem>
          <FormItem className="priority-wrap"
                    label={messages('finance-setting.key4')/*本位币*/} {...formItemLayout}>
            {getFieldDecorator('currencyCode',{
              rules: [{
                required: true
              }],
              initialValue: record.currencyCode ? record.currencyCode : this.props.company.baseCurrency
            })(
              <Select disabled placeholder={messages('common.select')} getPopupContainer={triggerNode => triggerNode.parentNode}>
                {
                  currencyList.map(item => {
                    return <Option key={item.currencyCode} title={item.currencyCode}>{item.currencyCode}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem className="priority-wrap"
                    label={messages('finance-setting.key150')/*借款类型*/} {...formItemLayout}>
            {getFieldDecorator('loanTypeId',{
              rules: [{
                required: true
              }],
              initialValue: record.loanTypeId ? record.loanTypeId : undefined
            })(
              <Select placeholder={messages('common.select')} getPopupContainer={triggerNode => triggerNode.parentNode}>
                {
                  typeList.map(item => {
                    return <Option key={item.id} title={item.description}>{item.description}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem className="priority-wrap"
                    label={messages('finance-setting.key155')/*最大上限总金额*/} {...formItemLayout}>
            {getFieldDecorator('amountMax',{
              rules: [{
                required: true,
                message: messages('finance-setting.key156')/*请输入最大上限总金额*/
              }],
              initialValue: record.amountMax ? record.amountMax : undefined
            })(
              <InputNumber min={0} precision={2} step={1} style={{width:'100%'}} placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company
  }
}

const wrappedLoanRule = Form.create()(LoanRule);
export default connect(mapStateToProps)(wrappedLoanRule);
